import React, { Component } from 'react';

class Homework extends Component {
    state = {
        bookArr: [{
            id: 1,
            bookname: '三国'
        },
        {
            id: 2,
            bookname: '水浒'
        }, {
            id: 3,
            bookname: '红楼'
        }],
        isshow: false, // 控制是否显示模态框
        id: '' // 数据的id
    }
    render() {
        const { bookArr, isshow } = this.state
        return (
            <div>
                <ul>
                    {
                        bookArr.map((item) => {
                            return <li key={item.id}>
                                <span>{item.id}</span>
                                <span>{item.bookname}</span>
                                <button onClick={() => { this.editFn(item) }}>编辑</button>
                                <button>删除</button>
                            </li>
                        })
                    }
                </ul>

                {/* 新增 */}
                <div>
                    <p> <input type='text' id='addinp' /></p>
                    <button onClick={this.addBookFn}>确认</button>
                </div>
                {/* 模态框 */}

                {isshow ? <div className='mask'>
                    <p>
                        <input type='text' id='editinp' />
                    </p>
                    <p>
                        <button>取消</button>
                        <button onClick={this.editSureFn}>确认</button>
                    </p>
                </div> : <></>
                }
            </div>
        );
    }
    // 添加
    addBookFn = () => {
        // 获取input 标签中的内容
        let inp = document.querySelector('#addinp');
        let obj = {
            id: this.state.bookArr[this.state.bookArr.length - 1].id + 1, // 保证id 永远不重复
            bookname: inp.value
        }
        // console.log(obj);
        this.state.bookArr.push(obj)
        this.setState({
            bookArr: this.state.bookArr
        })
    }
    // 点击编辑处理函数
    editFn(item) {
        console.log(item);
        // 显示模态框
        this.setState({
            isshow: true,
            id: item.id

        }, () => {
            // 数据的回填
            // console.log(document.querySelector('#editinp'));
            document.querySelector('#editinp').value = item.bookname

        })
    };
    // 编辑确认
    editSureFn = () => {
        // 获取到要修改那一条数据
        console.log(this.state.id);
        this.state.bookArr.forEach((item) => {
            if (item.id == this.state.id) {
                item.bookname = document.querySelector('#editinp').value
            }
        })

        this.setState({
            bookArr: this.state.bookArr,
            isshow: false
        })

    }
}

export default Homework;
